﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
namespace ModbusCommunicate
{

    public class ModBusByTcp:SendByTcp 
    {
        /// <summary>
        /// <para>主程序接收TCP事件：BusTransfer.MsgTransfer.Instance.Register<ModbusEvent>(this, action)</para>
        /// <para>主程序接收到数据：BusTransfer.MsgTransfer.Instance.Register<byte[]>(this, ModbusData)</para>
        /// </summary>
        /// <param name="data"></param>
        public ModBusByTcp(SendByTcp.InitData data )
        {
            ModBusByTcpInit(data);
        }


        /// <summary>
        /// JSON转换器
        /// </summary>
        JavaScriptSerializer JS = new JavaScriptSerializer();

        /// <summary>
        /// 使用TCP协议发送数据
        /// </summary>
        public SendByTcp SBT { get; private set; }

        /// <summary>
        /// TCP服务器基本信息
        /// </summary>
        public InitData SocketInfo { get; private set; }

        public  void   ModBusByTcpInit(SendByTcp.InitData data)
        {
            if (IsCorrectIP(data.ip) && data.port == 0 && data.register == null && data.heartbeat == null)
                throw new Exception("0");  //抛出0代表参数错误
            ModBus.SendModBusData smb = new ModbusCommunicate.ModBus.SendModBusData(sendbytes);
            MB = new ModbusCommunicate.ModBus(sendbytes);
            SocketInfo = data;
            SBT = new SendByTcp();
            SendByTcp.ReceiveSocketData RS = new SendByTcp.ReceiveSocketData(ReceiveBytes);
            SBT.delegateinit(RS);
            SBT.TCPConfig (SocketInfo);
        }

        private bool  sendbytes(byte[] data)
        {
           return  SBT.Send(data);
        }


        /// <summary>
        /// modbus协议处理实例
        /// </summary>
       public  ModBus MB;

        /// <summary>
        /// 判断字符串是否是ip地址
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        bool IsCorrectIP(string ip)
        {
            if (ip == null)
                return false;
            Regex rx = new Regex(@"((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d))))");
            return rx.IsMatch(ip);
        }

        /// <summary>
        /// 接收到的数据
        /// </summary>
        /// <param name="Data"></param>
        private void ReceiveBytes(byte[] Data)
        {
            MB.locks = 1;
            BusTransfer.MsgTransfer.Instance.Send(Data, SBT.TCPinfo.MR.reg_id +"@modbus");       
        }

        /// <summary>
        /// 同步连接连接服务器
        /// </summary>
        /// <returns></returns>
        public bool TcpConnect()
        {
          return   SBT.TCPStart();
        }

        /// <summary>
        /// 异步连接TCP服务器
        /// </summary>
        public void  AsyncTcpConnect()
        {
            SBT.AsyncTcpStart();
        }
  

        /// <summary>
        /// 增加一个modbus操作
        /// </summary>
        /// <param name="MS"></param>
        public void ADDTask(ModbusSend MS)
        {
            MB.AddModBus(MS);
            MB.SendModBus();
        }

        /// <summary>
        /// 移除一个modbus操作
        /// </summary>
        /// <param name="MS"></param>
        public void DELTask(ModbusSend MS)
        {
            MB.RemoveModBus(MS);
        }

    }
}
